<?php

namespace app\yue\home;

use GatewayClient\Gateway;

class Round extends Auth
{
    public function index()
    {
        $id = input('id/d');

        if (!$id) {
            return json([
                'err' => 1,
                'msg' => 'invalid id',
            ]);
        }

        $round        = model('yue_round');
        $res          = $round->find($id);
        $cash         = $res->cash;
        $is_host      = $res->host_id == $this->uid;
        $is_over      = $res->status == 2;
        $side         = $res->win_side;
        $round_member = model('yue_round_member');

        if ($is_over) {
            $items = $round_member->where(['rid' => $id, 'status' => ['>=', 1]])->order('side')->select();
        } else {
            $items = $round_member->where(['rid' => $id, 'status' => ['>=', 1]])->count();
        }

        $rank = model('yue_member')->where('id', $this->uid)->value('rank');
        // $rank_update = time() - $self->rank_update_time > 3600 * 24 * 7;
        // $rank_update = time() - $self->rank_update_time > 10;
        $rank_list = '';
        if ($rank == 0) {
            $rank_list = config('yue_rank');
            // array_shift($rank_list);
        }

        return json([
            'err'       => 0,
            'id'        => $id,
            'cash'      => $cash,
            'mode'      => $res->mode,
            'is_host'   => $is_host,
            'host_name' => $res->nickName,
            'is_over'   => $is_over,
            'win_side'  => $side,
            'items'     => $items,
            'rank'      => $rank,
            'rank_list' => $rank_list,
            'msg'       => 'success',
        ]);
    }

    public function create()
    {
        $cash = input('cash/d', 0);
        $mode = input('mode/d', 5);

        if ($cash > 200) {
            return json([
                'err' => 1,
                'msg' => 'beyound 200',
            ]);
        }

        $round   = model('yue_round');
        $set_fee = $cash;
        if ($cash) {
            $cash = $cash + $this->house_fee;
        }

        $cash = round($cash, 2);

        // trace('create:' . json_encode($this->member_info), 'error');

        $res = $round->save([
            'host_id'   => $this->uid,
            'mode'      => $mode,
            'openid'    => $this->member_info['openId'],
            'nickName'  => $this->member_info['nickName'],
            'avatarUrl' => $this->member_info['avatarUrl'],
            'cash'      => $cash,
            'set_fee'   => $set_fee,
        ]);

        if (!$res) {
            trace('create error:' . json_encode($this->member_info), 'error');
        }

        $rid = $round->id;

        return json([
            'err' => 0,
            'id'  => $rid,
            'msg' => 'success',
        ]);
    }

    public function winSide()
    {
        $id         = input('id/d');
        $side       = input('side/d');
        $round      = model('yue_round');
        $this_round = $round->find($id);

        if ($this_round->win_side > 0) {
            return json([
                'err' => 1,
                'msg' => '胜负已分',
            ]);
        }

        if ($this_round->status < 2) {
            return json([
                'err' => 1,
                'msg' => '游戏还没开始',
            ]);
        }

        if ($this_round->status == 3) {
            return json([
                'err' => 1,
                'msg' => '游戏过期已退款',
            ]);
        }

        $is_host = $this_round->host_id == $this->uid;
        if (!$is_host) {
            return json([
                'err' => 1,
                'msg' => 'not host',
            ]);
        }

        Gateway::sendToGroup($id, \json_encode(['type' => 'win_side', 'win_side' => $side]));

        $round->save(['win_side' => $side], ['id' => $id]);
        $members = model('yue_round_member')->where(['rid' => $id, 'status' => 1])->select();
        foreach ($members as $member) {
            $win_lose = $member['side'] == $side ? 1 : 2;
            $_member  = model('yue_member')->find($member['uid']);
            if ($win_lose == 1) {
                $_member->setInc('score', 100);
                $_member->setInc('win');
            } else {
                $_member->setInc('lose');
            }
            $member->save(['win_lose' => $win_lose]);
        }

        if ($this_round->set_fee > 0) {
            $pay        = $this->getWechatPay();
            $refund_fee = $this_round->set_fee * 100;
            foreach ($members as $v) {
                $res = $pay->refund($v['out_trade_no'], $v['transaction_id'], self::getBillno(), $v['total_fee'], $refund_fee);
                trace($res, 'error');
            }

            $result = $pay->transfers($this_round->openid, $this->house_fee * $this_round->mode * 100, self::getBillno(), '推荐奖励');
            trace($result, 'error');
        }

        return json([
            'err' => 0,
            'msg' => 'success',
        ]);
    }

    public function join()
    {
        $id     = input('id/d');
        $formid = input('formid');
        $this->addFormId($this->member_info['openId'], $formid);

        $round        = model('yue_round');
        $round_member = model('yue_round_member');

        $this_round = $round->find($id);

        if ($this_round->win_side > 0) {
            return json([
                'err' => 1,
                'msg' => '游戏已经结束',
            ]);
        }

        if ($this_round->status == 2) {
            return json([
                'err' => 1,
                'msg' => '游戏已经开始',
            ]);
        }

        if ($this_round->status == 3) {
            return json([
                'err' => 1,
                'msg' => '游戏过期已退款',
            ]);
        }

        if ($round_member->where('rid', $id)->count() >= $this_round->mode * 2) {
            return json([
                'err' => 1,
                'msg' => '人员已满',
            ]);
        }

        if ($round_member->where(['rid' => $id, 'uid' => $this->uid])->count()) {
            return json([
                'err' => 1,
                'msg' => '您已经加入了',
            ]);
        }

        $cash = $this_round->cash;
        if ($cash > 0) {
            $res = $this->payment($cash, $id);
            if ($res) {
                return json([
                    'err'     => 0,
                    'options' => $res,
                    'msg'     => 'success',
                ]);
            } else {
                return json([
                    'err' => 1,
                    'msg' => '支付失败',
                ]);
            }
        } else {
            if (!isset($this->member_info['uid'])) {
                return json([
                    'err' => 1,
                    'msg' => '加入失败，请重试',
                ]);
            }

            $this->member_info['rid'] = $id;
            $round_member->save($this->member_info);

            $this->chkResult($id);
        }

        return json([
            'err' => 0,
            'msg' => '加入成功',
        ]);
    }

    public function rank()
    {
        $rank = input('rank/d');
        if ($rank > count(config('yue_rank')) - 1 || $rank < 0) {
            return json([
                'err' => 1,
                'msg' => '修改失败',
            ]);
        }

        if (time() - model('yue_member')->where('id', $this->uid)->value('rank_update_time') < $this->rank_change_interval) {
            return json([
                'err' => 1,
                'msg' => '还没到修改时间',
            ]);
        }

        model('yue_member')->save(['rank' => $rank, 'rank_update_time' => time()], ['id' => $this->uid]);

        return json([
            'err' => 0,
            'msg' => '修改成功',
        ]);
    }

    public function setGid()
    {
        $gid = $this->getGid();
        $rid = input('id/d');

        $_round = model('yue_round')->find($rid);
        if(!$_round->openGid){
            $_round->save(['openGid' => $gid]);
        }

        return json([
            'err' => 0,
            'gid' => $gid,
            'msg' => 'success',
        ]);
    }

    public function rules()
    {
        $text = module_config('yue.rules');
        $text = str_replace('<img src="', '<img width="100%" src="' . $this->request->domain(), $text);

        return json([
            'title' => '规则',
            'msg'   => $text,
        ]);
    }

    protected function payment($cash, $rid)
    {
        $pay = $this->getWechatPay();
        // 获取预支付ID
        $prepayid = $pay->getPrepayId($this->member_info['openId'], '押金', self::getBillno(), $cash * 100, url('notify/index', ['rid' => $rid], '', true), $trade_type = "JSAPI");

        if ($prepayid === false) {
            // 接口失败的处理
            return false;
        } else {
            // 接口成功的处理
            $options = $pay->createMchPay($prepayid);
            return $options;
        }
    }
}
